package com.zml.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.widget.PdfPageCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;


public class ReadPdf {

    private static Logger log = LoggerFactory.getLogger(ReadPdf.class);


    public static boolean readPdf(String filePath) {
        log.info("正在解析Pdf的文字……");
        List<Object> list = new ArrayList<>();
        PdfDocument doc = null;
        try {
//            PdfReader reader = new PdfReader(filePath);
//            int pageNum = reader.getNumberOfPages();
            doc = new PdfDocument();
            doc.loadFromFile(filePath);
            PdfPageCollection pages = doc.getPages();
            int pageNumber = pages.getCount();
            for (int i = 0; i < pageNumber; i++) {
                list.add(pages.get(i).extractText(false)
                        .replaceAll("\n", "")
                        .replaceAll(" ", "")
                        .replaceAll("\t", "")
                        .replaceAll("\r", ""));
            }
            JSONArray jsonObject = JSONArray.parseArray(JSON.toJSONString(list));
            String jsonString = jsonObject.toString();
            Path path = Paths.get(filePath);
            String onlyName = PdfUtil.getOnlyName(path);
            Path jsonFilePath = Paths.get(path.getParent().toString(), onlyName, onlyName + ".json");
            createJsonFile(jsonString, jsonFilePath.toString());
        } catch (Exception e) {
            log.error("PDF文件文字提取失败！",e);
            if (doc != null) {
                doc.close();
            }
            return false;
        }
        return true;
    }


    public static boolean createJsonFile(String jsonString, String filePath) {
        boolean flag = true;

        try {
            File file = new File(filePath);

            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            jsonString = jsonString.replaceAll("\",", "\",\r\n");
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

}
